package com.ouman.luoliluoli.mainfragments;

import android.animation.Animator;
import android.content.Context;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.Toast;

import com.ouman.luoliluoli.MainActivity;
import com.ouman.luoliluoli.R;
import com.ouman.luoliluoli.adapters.HotRecyclerViewAdapter;
import com.ouman.luoliluoli.models.HotNewsModel;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ouman.luoliluoli.utils.NetworkHelper;

import static android.widget.Toast.LENGTH_SHORT;

public class HotFragment extends Fragment {

    private OnFragmentInteractionListener mListener;

    private RecyclerView recyclerView;
    private HotRecyclerViewAdapter adapter;
    private ArrayList<HotNewsModel> newsArray;
    private SwipeRefreshLayout swipeRefreshLayout;
    private String LAST_UPDATE = "201409";

    private NetworkHelper networkHelper;

    public HotFragment() {
    }

    public static HotFragment newInstance(String param1, String param2) {
        HotFragment fragment = new HotFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ((MainActivity) getActivity()).disableCollapsingLayoutTitle();
        ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("首页");


        View rootView = inflater.inflate(R.layout.fragment_hot, container, false);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.hot_recyclerview);

        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                // 圆形动画的x坐标  位于View的中心
                int cx = (recyclerView.getLeft() + recyclerView.getRight()) / 2;

                //圆形动画的y坐标  位于View的中心
                int cy = (recyclerView.getTop() + recyclerView.getBottom()) / 2;

                //起始大小半径
                float startX=0f;

                //结束大小半径 大小为图片对角线的一半
                float startY= (float) Math.sqrt(cx*cx+cy*cy);
                Animator animator= ViewAnimationUtils.createCircularReveal(recyclerView,cx,cy,startX,startY);

                //在动画开始的地方速率改变比较慢,然后开始加速
                animator.setInterpolator(new AccelerateInterpolator());
                animator.setDuration(600);
                animator.start();
            }
        });

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        networkHelper = new NetworkHelper();

        newsArray = new ArrayList<>();
        //add swipe refresh on recycler view
        swipeRefreshLayout = (SwipeRefreshLayout) getActivity().findViewById(R.id.swipeLayout_hot_recylcerview);
        swipeRefreshLayout.setSize(SwipeRefreshLayout.DEFAULT);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_red_dark, android.R.color.holo_red_light,
                android.R.color.holo_blue_light, android.R.color.holo_purple);
        swipeRefreshLayout.setProgressViewEndTarget(true, 200);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // check network

                if (networkHelper.isConnect(getActivity())){
                    new  Thread(getHttpThread).start();
                }else {
                    Toast.makeText(getActivity(), "no connection, please check your network.", Toast.LENGTH_SHORT).show();
                }
                swipeRefreshLayout.setRefreshing(false);
            }
        });
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.recyclerview_spacing);
        recyclerView.addItemDecoration(new SpaceItemDecoration(spacingInPixels));

        adapter = new HotRecyclerViewAdapter(getActivity(), newsArray);
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int y;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == recyclerView.SCROLL_STATE_IDLE && y>0){
                    ((MainActivity) getActivity()).hideFloatingActionButton();
                }else if(newState == recyclerView.SCROLL_STATE_IDLE && y<0){
                    ((MainActivity) getActivity()).setAppBarElevation(0);
                    ((MainActivity) getActivity()).showFloatingActionButton();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                y = dy;
                //上滑隐藏fab
                if (dy > 0)
                {
                    ((MainActivity) getActivity()).hideFloatingActionButton();
                }else{
                    ((MainActivity) getActivity()).setAppBarElevation(0);
                    ((MainActivity) getActivity()).showFloatingActionButton();
                }
            }
        });

        if (networkHelper.isConnect(getContext())){
            new  Thread(getHttpThread).start();
        }else {
            Toast.makeText(getActivity(), "貌似没有网络连接啊", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }

    public class SpaceItemDecoration extends RecyclerView.ItemDecoration{
        private int space;
        public SpaceItemDecoration(int space) {
            this.space = space;
        }
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            if(parent.getChildPosition(view) != 0)
                outRect.top = space;
        }
    }

    private  Thread getHttpThread = new Thread(){
        public void run(){
            //In here we solve http request to get data
            swipeRefreshLayout.setRefreshing(true);
            HttpURLConnection connection = null;
            try {
                String urlAPI = "http://news-at.zhihu.com/api/4/news/latest";
                URL url = new URL(urlAPI);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                if (connection.getResponseCode() == 200){
                    InputStream is = connection.getInputStream();
                    String result = IOUtils.toString(is);
                    System.out.println(result);
                    is.close();
                    JSONObject jsonObject = new JSONObject(result);
                    //每次请求，都获取一下日期，对比本地的LAST_UPDATE标志位
                    String date = jsonObject.getString("date");
//                    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    if(LAST_UPDATE.equals(date)){
                        //如果上次日期和网络新获取到的相同，那么就不要更新界面了
                        Message msg = Message.obtain();
                        msg.what = 1;
                        getHttpHandler.sendMessage(msg);
                    }else{
                        //如果上次日期与网络不同，那么说明网络有更新了，这个时候我们就要更新界面
                        JSONArray jArray = jsonObject.getJSONArray("stories");
                        for (int i=0; i<jArray.length(); i++){
                            try {
                                JSONObject dataObject = jArray.getJSONObject(i);
                                String title = dataObject.getString("title");

                                ArrayList<String> imagesUrl = new ArrayList();
                                JSONArray images = dataObject.getJSONArray("images");
                                //!!!!这里是整个显示的核心部分，images解析到JSONArray，然后JSONArray遍历到ArrayList
                                //但是注意，这里从JSONArray中提取元素一定要是字符串！！！！
                                for (int j=0; j<images.length();j++){
                                    imagesUrl.add(images.getString(j));
                                }
                                int id = dataObject.getInt("id");
                                HotNewsModel news = new HotNewsModel();
                                news.setTitle(title);

                                // TODO date like 20170521 must change into -> 5月21号
                                news.setDate(date.substring(0, 4) + "年" + date.substring(4, 6) + "月" + date.substring(6, 8)+ "日");
                                news.setId(id);
                                news.setImages(imagesUrl);
                                newsArray.add(0, news);

                                //更新一下标识位
                                LAST_UPDATE = date;
//                                Toast.makeText(getContext(), "now last update: "+LAST_UPDATE, Toast.LENGTH_SHORT).show();

                            } catch (JSONException e){
                            }
                        }
                        if (!newsArray.isEmpty()){
                            Message msg = Message.obtain();
                            msg.what = 0;
                            getHttpHandler.sendMessage(msg);
                        }

                    }

                }
            } catch (IOException e){
                e.printStackTrace();
            } catch (JSONException e){
                e.printStackTrace();
            } finally{
                if (connection != null){
                    connection.disconnect();
                }
            }

        }
    };
    private Handler getHttpHandler = new Handler(){
        public void handleMessage(Message msg){
            if (msg.what == 0){
                //add data stop refresher and send to adapter data
                //changed
                adapter.notifyDataSetChanged();
                recyclerView.setAdapter(adapter);
                swipeRefreshLayout.setRefreshing(false);
            }else if (msg.what == 1){
                Toast.makeText(getActivity(), "已经是最新了哦", LENGTH_SHORT).show();
                swipeRefreshLayout.setRefreshing(false);
            }
        }
    };


}


